<template>
	<div class="user-list">
		<div style="margin: 20px 0">
			<el-button type="primary" @click="addData">添加扩展阅读</el-button>
		</div>
		<el-table :data="dataList" style="width: 100%">
			<el-table-column type="index" width="50" />
			<el-table-column prop="title" label="标题" min-width="180" />
			<el-table-column prop="type" label="类型" min-width="180">
				<template #default="scope">
					<el-tag type="warning" effect="dark">
						{{ scope.row.type }}</el-tag
					>
				</template>
			</el-table-column>
			<el-table-column prop="desc" label="简介" min-width="180" />
			<el-table-column
				prop="createTime"
				label="创建时间"
				min-width="180"
			/>
			<el-table-column prop="cover" label="封面" min-width="180">
				<template #default="scope">
					<img
						v-if="scope.row.cover"
						:src="'http://localhost:3000/' + scope.row.cover"
						style="width: 120px; height: 120px"
					/>
				</template>
			</el-table-column>
			<el-table-column prop="file" label="文件" min-width="180">
				<template #default="scope">
					<el-button type="primary" @click="handleOpenFile(scope.row)"
						>打开文件</el-button
					>
				</template>
			</el-table-column>
			<el-table-column prop="status" label="状态" min-width="180">
				<template #default="scope">
					<el-tag type="" effect="dark">
						{{
							scope.row.status == 0
								? "未审核"
								: scope.row.status == 1
								? "审核通过"
								: "审核不通过"
						}}</el-tag
					>
				</template>
			</el-table-column>
			<el-table-column label="操作" min-width="180">
				<template #default="scope">
					<el-button type="primary" @click="updateData(scope.row)"
						>编辑</el-button
					>
					<el-button type="danger" @click="delData(scope.row)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			class="pagination"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="query.pageNum"
			:page-sizes="[10, 20, 30, 40]"
			:page-size="query.pageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
		/>
		<el-dialog
			v-model="dialogInfo.visible"
			:title="dialogInfo.title"
			width="30%"
			:close-on-click-modal="false"
			:destroy-on-close="true"
		>
			<el-form
				ref="ruleFormRef"
				:model="form"
				:rules="rules"
				label-width="80px"
			>
				<el-form-item label="标题" prop="title">
					<el-input v-model="form.title" placeholder="请输入标题" />
				</el-form-item>
				<el-form-item label="类型" prop="extendArticleTypeId">
					<el-select
						v-model="form.extendArticleTypeId"
						class="m-2"
						placeholder="请选择类型"
					>
						<el-option
							v-for="item in typeList"
							:key="item.id"
							:label="item.title"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="简介" prop="desc">
					<el-input v-model="form.desc" type="textarea" :rows="4" />
				</el-form-item>
				<el-form-item label="内容" prop="content">
					<div style="border: 1px solid #ccc; height: 500px">
						<Toolbar
							style="border-bottom: 1px solid #ccc"
							:editor="editorRef"
							:defaultConfig="toolbarConfig"
							mode="simple"
						/>
						<Editor
							style="height: 320px; overflow-y: hidden"
							v-model="form.content"
							:defaultConfig="editorConfig"
							mode="simple"
							@onCreated="handleCreated"
						/>
					</div>
				</el-form-item>
				<el-form-item label="封面" prop="cover">
					<el-upload
						class="avatar-uploader"
						action="http://localhost:3000/api/extendArticle/upload"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
					>
						<img
							v-if="form.cover"
							:src="'http://localhost:3000/' + form.cover"
							class="avatar"
						/>
						<el-icon v-else class="avatar-uploader-icon"
							><Plus
						/></el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="pdf文件" prop="file">
					<el-upload
						class="avatar-uploader"
						action="http://localhost:3000/api/extendArticle/upload"
						:show-file-list="false"
						:on-success="handleFileSuccess"
						accept=".pdf"
					>
						<el-button type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select
						v-model="form.status"
						class="m-2"
						placeholder="请选择状态"
					>
						<el-option
							v-for="item in statusList"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm(ruleFormRef)"
						>确定
					</el-button>
					<el-button @click="resetForm(ruleFormRef)">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script setup>
import { onMounted, reactive, ref, shallowRef } from "vue";
import { add, del, list, update } from "@/api/extendArticle";
import { list as getTypeData } from "@/api/extendArticleType";

import { ElMessage, dayjs } from "element-plus";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

const ruleFormRef = ref();
const toolbarConfig = {};
const editorConfig = {
	placeholder: "请输入简介...",
	MENU_CONF: {
		uploadImage: {
			server: "http://localhost:3000/api/extendArticle/upload",
			"tenant-id": "1",
			fieldName: "file",
			customInsert(res, insertFn) {
				if (res.code === 200) {
					const api = "http://localhost:3000/";
					insertFn(api + res.result, null, api + res.result);
				}
			},
		},
	},
};
const total = ref(0);
const query = reactive({
	pageSize: 10,
	pageNum: 1,
});
const editorRef = shallowRef();
const dataList = ref([]);
const typeList = ref([]);
const statusList = ref([
	{ id: 0, name: "未审核" },
	{ id: 1, name: "通过" },
	{ id: 2, name: "不通过" },
]);
const dialogInfo = reactive({
	title: "添加扩展阅读",
	visible: false,
	type: 0,
});

const form = reactive({
	title: "",
	content: "",
	desc: "",
	extendArticleTypeId: "",
	file: "",
	cover: "",
	status: 0,
	id: 0,
});

const rules = reactive({
	title: [{ required: true, message: "请输入标题", trigger: "blur" }],
	content: [{ required: true, message: "请输入内容", trigger: "blur" }],
	desc: [{ required: true, message: "请输入简介", trigger: "blur" }],
	extendArticleTypeId: [
		{ required: true, message: "请选择类型", trigger: "blur" },
	],
	cover: [{ required: true, message: "请上传封面", trigger: "blur" }],
	file: [{ required: true, message: "请上传pdf文件", trigger: "blur" }],
});

onMounted(() => {
	handleGetTypeData();
});

const handleCreated = editor => {
	editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleGetTypeData = async () => {
	try {
		const res = await getTypeData();
		typeList.value = res.result.list;
		if (typeList.value.length) {
			getData();
		}
	} catch (err) {
		console.error(err);
	}
};
const getData = async () => {
	try {
		const res = await list(query);
		dataList.value = res.result.list.map(ele => {
			return {
				...ele,
				type: typeList.value.find(
					item => item.id === ele.extendArticleTypeId
				).title,
				createTime: dayjs(ele.createTime).format("YYYY-MM-DD"),
			};
		});
		total.value = res.result.count;
	} catch (err) {
		console.error(err);
	}
};
const handleSizeChange = newSize => {
	query.pageSize = newSize;
	getData();
};

const handleCurrentChange = newPage => {
	query.pageNum = newPage; // Reset to first page on size change
	getData();
};
const addData = () => {
	for (const key in form) {
		form[key] = "";
	}
	dialogInfo.type = 0;
	dialogInfo.title = "添加扩展阅读";
	dialogInfo.visible = true;
};

const updateData = row => {
	for (const key in form) {
		form[key] = row[key];
	}
	dialogInfo.type = 1;
	dialogInfo.title = "修改扩展阅读";
	dialogInfo.visible = true;
};

const submitForm = async formEl => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			if (!dialogInfo.type) {
				await add({
					title: form.title,
					content: form.content,
					desc: form.desc,
					extendArticleTypeId: form.extendArticleTypeId,
					cover: form.cover,
					status: form.status ? form.status : 0,
				});
				ElMessage.success("添加成功");
				resetForm(ruleFormRef.value);
				getData();
				return;
			}

			await update(form);
			ElMessage.success("修改成功");
			resetForm(ruleFormRef.value);
			getData();
		}
	});
};

const delData = async row => {
	await del({
		id: row.id,
	});
	ElMessage.success("删除成功");
	getData();
};

const resetForm = formEl => {
	if (!formEl) return;
	formEl.resetFields();
	dialogInfo.visible = false;
};

const handleAvatarSuccess = response => {
	form.cover = response.result;
};
const handleFileSuccess = response => {
	form.file = response.result;
	ElMessage.success("上传成功");
};
const handleOpenFile = row => {
	window.open("http://localhost:3000/" + row.file);
};
</script>

<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
